import baseCss from './base.css?raw'
const baseStyle = new CSSStyleSheet();
baseStyle.replace(baseCss)

class BaseElement extends HTMLElement {
    constructor() {
        super();
        this.findParent();


    }


    findParent() {
        // 遍历父级直到找到目标组件
        let parent = this.getRootNode().host;
        while (parent && !(parent instanceof BaseElement)) {
            if (parent.classList.contains("ai-chat-container")) {
                parent = null;
                break;
            }
            parent = parent.getRootNode().host;
        }
        if (parent) {
            this.injectData = parent.injectData ?? {};
        }
    }

    injectData = {}

    get chatInstance() {
        if (!this.injectData?.chatInstance) {
            this.findParent();
        }
        return this.injectData?.chatInstance;
    }


    showConfirm({ title, content, confirmText, cancelText} = {}) {

        return this.chatInstance.confirmDialog.showConfirm({ title, content, confirmText, cancelText});
    }



    /**
     * 向子组件注入数据
     * @param element
     * @param key
     * @param value
     * @param recursion 是否递归注入
     */
    inject(element, key, value, recursion) {
        element.receive(key, value, recursion);
    }

    /**
     * 接收注入的数据
     * @param key
     * @param value
     * @param recursion
     */
    receive(key, value, recursion = true) {
        this.injectData[key] = value;
        if (this.onReceive) {
            this.onReceive(key, value);
        }
        if (recursion) {
            this.shadowRoot.querySelectorAll('*').forEach(element => {
                //如果 element是BaseElement的子组件，则注入数据
                if (element instanceof BaseElement) {
                    this.inject(element, key, value, recursion);
                }
            });
        }
    }



}

/**
 * 聊天状态枚举
 */
class ChatStatus {

    static IS_WAITING = Symbol("等待中");
    static IS_RECEIVING = Symbol("接收中");
    static IS_READY = Symbol("准备完毕");
    static DISCONNECTED = Symbol("连接断开");

}

export {BaseElement, ChatStatus, baseStyle};